<template>
  <div class="page-container">
    <div class="page-header">
      <h2>任务管理</h2>
      <div class="header-actions">
        <div class="search-box">
          <input type="text" v-model="searchKeyword" placeholder="搜索任务名称" @input="handleSearch" />
          <select v-model="filterType" @change="handleSearch">
            <option value="">全部类型</option>
            <option value="vocabulary">词汇练习</option>
            <option value="reading">阅读理解</option>
            <option value="listening">听力训练</option>
            <option value="speaking">口语练习</option>
            <option value="writing">写作任务</option>
          </select>
        </div>
        <router-link to="/teacher/tasks/create" class="btn btn-primary"> 创建任务 </router-link>
      </div>
    </div>

    <div class="tasks-container">
      <div class="task-list" v-if="filteredTasks.length">
        <div v-for="task in filteredTasks" :key="task.id" class="task-item">
          <div class="task-header">
            <h3 class="task-title">{{ task.title }}</h3>
            <div class="task-actions">
              <button class="btn-icon" @click="editTask(task)">
                <i class="icon">✏️</i>
              </button>
              <button class="btn-icon" @click="deleteTask(task)">
                <i class="icon">🗑️</i>
              </button>
            </div>
          </div>
          <div class="task-info">
            <span class="task-type">{{ getTaskTypeName(task.type) }}</span>
            <span class="task-status" :class="getStatusClass(task)">
              {{ getStatusText(task) }}
            </span>
          </div>
          <div class="task-details">
            <div class="detail-item">
              <span class="label">开始时间：</span>
              <span>{{ formatDate(task.startTime) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">截止时间：</span>
              <span>{{ formatDate(task.endTime) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">发布班级：</span>
              <span>{{ getClassNames(task.classes) }}</span>
            </div>
          </div>
          <div class="task-description">
            {{ task.description }}
          </div>
          <div class="task-resources" v-if="task.resources?.length">
            <div class="label">学习资源：</div>
            <div class="resource-list">
              <a v-for="resource in task.resources" :key="resource.url" :href="resource.url" class="resource-item" target="_blank">
                <i class="icon">📄</i>
                <span>{{ resource.name }}</span>
              </a>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="empty-state">
        <p>暂无任务数据</p>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <div class="dialog-overlay" v-if="showDeleteDialog" @click="cancelDelete">
      <div class="dialog-content" @click.stop>
        <h3>确认删除</h3>
        <p>确定要删除任务"{{ taskToDelete?.title }}"吗？此操作不可恢复。</p>
        <div class="dialog-actions">
          <button class="btn btn-secondary" @click="cancelDelete">取消</button>
          <button class="btn btn-danger" @click="confirmDelete">确认删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { taskApi } from '@/api'

export default {
  name: 'TaskManagement',
  data() {
    return {
      tasks: [],
      searchKeyword: '',
      filterType: '',
      showDeleteDialog: false,
      taskToDelete: null,
      classList: [
        { id: 1, name: '初一(1)班' },
        { id: 2, name: '初一(2)班' },
        { id: 3, name: '初一(3)班' },
        { id: 4, name: '初二(1)班' },
        { id: 5, name: '初二(2)班' }
      ]
    }
  },
  computed: {
    filteredTasks() {
      return this.tasks.filter((task) => {
        const matchKeyword =
          task.title.toLowerCase().includes(this.searchKeyword.toLowerCase()) ||
          task.description.toLowerCase().includes(this.searchKeyword.toLowerCase())
        const matchType = !this.filterType || task.type === this.filterType
        return matchKeyword && matchType
      })
    }
  },
  methods: {
    async fetchTasks() {
      try {
        const response = await taskApi.getTasks()
        // 确保 tasks 始终是数组
        this.tasks = Array.isArray(response.data) ? response.data : []

        // 如果没有数据，显示提示
        if (this.tasks.length === 0) {
          this.$message.info('暂无任务数据')
        }
      } catch (error) {
        console.error('获取任务列表失败:', error)
        this.$message.error('获取任务列表失败，请检查网络连接')
        this.tasks = [] // 出错时设置为空数组
      }
    },
    handleSearch() {
      // 搜索和筛选逻辑由计算属性处理
    },
    editTask(task) {
      this.$router.push({ path: `/teacher/tasks/create`, query: { task: JSON.stringify(task) } })
    },
    deleteTask(task) {
      this.taskToDelete = task
      this.showDeleteDialog = true
    },
    async confirmDelete() {
      if (!this.taskToDelete) return

      try {
        await taskApi.deleteTask(this.taskToDelete.id)
        this.$message.success('删除成功')
        this.tasks = this.tasks.filter((task) => task.id !== this.taskToDelete.id)
      } catch (error) {
        console.error('删除任务失败:', error)
        this.$message.error('删除任务失败')
      } finally {
        this.cancelDelete()
      }
    },
    cancelDelete() {
      this.showDeleteDialog = false
      this.taskToDelete = null
    },
    getTaskTypeName(type) {
      const typeMap = {
        vocabulary: '词汇练习',
        reading: '阅读理解',
        listening: '听力训练',
        speaking: '口语练习',
        writing: '写作任务'
      }
      return typeMap[type] || type
    },
    getStatusClass(task) {
      const now = new Date()
      const start = new Date(task.startTime)
      const end = new Date(task.endTime)

      if (now < start) return 'not-started'
      if (now > end) return 'ended'
      return 'in-progress'
    },
    getStatusText(task) {
      const now = new Date()
      const start = new Date(task.startTime)
      const end = new Date(task.endTime)

      if (now < start) return '未开始'
      if (now > end) return '已结束'
      return '进行中'
    },
    formatDate(dateStr) {
      const date = new Date(dateStr)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    getClassNames(classIds) {
      return classIds
        .map((id) => this.classList.find((cls) => cls.id === id)?.name)
        .filter(Boolean)
        .join('、')
    }
  },
  created() {
    this.fetchTasks()
  }
}
</script>

<style scoped>
.page-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-box {
  display: flex;
  gap: 12px;
}

.search-box input,
.search-box select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
}

.btn {
  padding: 8px 16px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  text-decoration: none;
}

.btn-primary {
  background: #409eff;
  color: white;
}

.btn-primary:hover {
  background: #66b1ff;
}

.btn-secondary {
  background: #f4f4f5;
  color: #606266;
}

.btn-danger {
  background: #f56c6c;
  color: white;
}

.btn-danger:hover {
  background: #f78989;
}

.btn-icon {
  padding: 4px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  opacity: 0.7;
  transition: opacity 0.3s;
}

.btn-icon:hover {
  opacity: 1;
}

.task-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.task-item {
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  transition: all 0.3s;
}

.task-item:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.task-title {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.task-actions {
  display: flex;
  gap: 8px;
}

.task-info {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.task-type {
  padding: 2px 8px;
  background: #ecf5ff;
  color: #409eff;
  border-radius: 4px;
  font-size: 12px;
}

.task-status {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.not-started {
  background: #f4f4f5;
  color: #909399;
}

.in-progress {
  background: #f0f9eb;
  color: #67c23a;
}

.ended {
  background: #fef0f0;
  color: #f56c6c;
}

.task-details {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 12px;
}

.detail-item {
  font-size: 14px;
  color: #606266;
}

.label {
  color: #909399;
  margin-right: 4px;
}

.task-description {
  font-size: 14px;
  color: #606266;
  margin-bottom: 16px;
  line-height: 1.6;
}

.task-resources {
  border-top: 1px solid #ebeef5;
  padding-top: 12px;
}

.resource-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.resource-item {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
  text-decoration: none;
  transition: all 0.3s;
}

.resource-item:hover {
  background: #ecf5ff;
  color: #409eff;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #909399;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  padding: 24px;
  border-radius: 8px;
  width: 400px;
}

.dialog-content h3 {
  margin: 0 0 16px 0;
  color: #303133;
}

.dialog-content p {
  margin: 0 0 24px 0;
  color: #606266;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
